const cloud = require('wx-server-sdk');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});

const db = cloud.database();
const _ = cloud.database().command;

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  const user = await db.collection("user").where({
    openid:wxContext.OPENID,
  }).get()

  if(user.data.length == 0)
  {
    return {
      code:401,
      data:{},
      msg:"have not login"
   }
  }
  
  if(user.data[0].status != 0)
  {
    return {
      code:401,
		 data:{},
		 msg:"no privilege"
    }
  }

  let k = new Date()
  let gt = k.valueOf()- 21600000

  const res = await db.collection("timeTable").where({
    timestamp:_.gt(gt)
  }).orderBy("timestamp","asc").limit(98).field({
    _id:true,
    timestamp:true,
  }).get()
  
    let data = res.data
    let pre = null
    let pre_hour = null
    
    if(data.length != 0)
    {
        pre = data[0].timestamp
    }
    else
    {
      return {
        code:404,
        data:{},
        msg:"empty timetable"
      }
    }

    pre_hour = new Date(pre).getHours()

    if(pre_hour%6 != 0 || pre_hour == 0 || pre%3600000 != 0)
    {
      const result = await db.collection("timeTable").where({
        timestamp:_.gte(pre)
      }).remove()

      return {
        code:201,
        data:result,
        msg:"check the error"
      }
    }

    let i = 1 
    for(;i < data.length;i++)
    { 
      if(pre_hour == 6 || pre_hour == 12)
      {
        pre += 21600000
        pre_hour += 6
        if(data[i].timestamp != pre)
        {
          break
        }
      }
      else if(pre_hour == 18)
      {
        pre += 43200000
        pre_hour = 6 
        if(data[i].timestamp != pre)
        {
          break
        }
      }
    }
    if(i != data.length)
    {
      const result = await db.collection("timeTable").where({
        timestamp:_.gte(pre)
      }).remove()

      return {
        code:201,
        data:result,
        msg:"check the error"
      }
    }

    return {
      code:200,
      data:{},
      msg:"no error!"
    }
};
